import React, { useState, useEffect } from 'react';
import { Layout, Typography, Space, Avatar, Dropdown, Button, message, Menu } from 'antd';
import { Routes, Route, useNavigate, useLocation } from 'react-router-dom';
import { 
  UserOutlined, 
  LogoutOutlined, 
  SettingOutlined,
  EditOutlined,
  FileTextOutlined,
  HomeOutlined,
  AppstoreOutlined
} from '@ant-design/icons';
import { getUser, removeToken } from '../utils';
import Home from '../pages/Home/Home';
import Articles from '../pages/Articles/Articles';
import CreateArticle from '../pages/CreateArticle/CreateArticle';
import Works from '../pages/Works/Works';
import AiEditorTest from '../pages/AiEditorTest';
import AttachmentTest from '../pages/AttachmentTest';
import authService from '../services/authService';

const { Header, Content, Sider } = Layout;
const { Title } = Typography;

const MainLayout = () => {
  const [user, setUser] = useState(null);
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const currentUser = getUser();
    setUser(currentUser);
  }, []);

  const handleLogout = async () => {
    try {
      await authService.logout();
      message.success('已退出登录');
      navigate('/login', { replace: true });
    } catch (error) {
      console.error('退出登录失败:', error);
      // 即使API调用失败，也要清除本地token
      removeToken();
      navigate('/login', { replace: true });
    }
  };

  const handleSave = (articleData) => {
    console.log('保存作品:', articleData);
    // 这里可以调用API保存到数据库
    message.success('作品已保存');
  };

  const handlePublish = (articleData) => {
    console.log('发布作品:', articleData);
    // 这里可以调用API发布作品
    message.success('作品已发布');
  };

  // 导航菜单项
  const menuItems = [
    {
      key: '/',
      icon: <HomeOutlined />,
      label: '首页',
    },
    {
      key: '/articles',
      icon: <FileTextOutlined />,
      label: '作品管理',
    },
    {
      key: '/works',
      icon: <EditOutlined />,
      label: '创建作品',
    }
  ];

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
      onClick: () => {
        message.info('个人资料功能开发中');
      }
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '设置',
      onClick: () => {
        message.info('设置功能开发中');
      }
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout
    }
  ];

  const handleMenuClick = ({ key }) => {
    navigate(key);
  };

  return (
    <Layout className="main-layout">
      <Header className="main-header">
        <div className="header-content">
          <div className="header-left">
            <Title level={3} style={{ color: 'white', margin: 0 }}>
              <AppstoreOutlined style={{ marginRight: 8 }} />
              作品发布系统
            </Title>
          </div>
          
          <div className="header-right">
            <Space size="middle">
              {user && (
                <Dropdown
                  menu={{ items: userMenuItems }}
                  placement="bottomRight"
                  trigger={['click']}
                >
                  <div className="user-info">
                    <Space>
                      <Avatar 
                        src={user.avatar_url} 
                        icon={<UserOutlined />}
                        size="small"
                      />
                      <span style={{ color: 'white' }}>
                        {user.username}
                      </span>
                    </Space>
                  </div>
                </Dropdown>
              )}
            </Space>
          </div>
        </div>
      </Header>
      
      <Layout>
        <Sider 
          width={200} 
          className="main-sider"
          collapsible
          collapsed={collapsed}
          onCollapse={setCollapsed}
          theme="light"
        >
          <Menu
            mode="inline"
            selectedKeys={[location.pathname]}
            items={menuItems}
            onClick={handleMenuClick}
            style={{ height: '100%', borderRight: 0 }}
          />
        </Sider>
        
        <Content className="main-content">
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/articles" element={<Articles />} />
            <Route 
              path="/works" 
              element={<Works />} 
            />
            <Route 
              path="/editor" 
              element={<CreateArticle />} 
            />
            <Route 
              path="/create" 
              element={<CreateArticle />} 
            />
            <Route 
              path="/editor/:id" 
              element={<CreateArticle />} 
            />
            <Route 
              path="/aieditor-test" 
              element={<AiEditorTest />} 
            />
            <Route 
              path="/attachment-test" 
              element={<AttachmentTest />} 
            />
          </Routes>
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLayout;